using System;
using Google.Protobuf;
using System.IO;


public class ProtoBufUtil
{
    //将对象序列化成字节数组
    public static byte[] ObjectToBytes<T>(T instance) where T : IMessage<T>, new()
    {
        try
        {
            byte[] array;
            if (instance == null)
            {
                array = new byte[0];
            }
            else
            {
                MemoryStream memoryStream = new MemoryStream();

                //序列化
                instance.WriteTo(memoryStream);
                array = new byte[memoryStream.Length];
                memoryStream.Position = 0L;
                memoryStream.Read(array, 0, array.Length);
                memoryStream.Dispose();
            }

            return array;

        }
        catch (Exception ex)
        {
            return new byte[0];
        }
    }
    //将信息反序列化成对象
    public static T BytesToObject<T>(byte[] bytesData) where T : IMessage<T>, new()
    {
        if (bytesData.Length == 0)
        {
            return default(T);
        }
        try
        {
            MemoryStream memoryStream = new MemoryStream();
            memoryStream.Write(bytesData, 0, bytesData.Length);
            memoryStream.Position = 0L;
            // T result = Serializer.Deserialize<T>(memoryStream);
            T result = new T();
            result.MergeFrom(memoryStream);
            memoryStream.Dispose();
            return result;
        }
        catch (Exception ex)
        {
            return default(T);
        }
    }
}